//var BOSH_SERVICE = 'http://127.0.0.1:7070/http-bind/';
//var BOSH_SERVICE='http://ddword.gffunction.cn:7070/http-bind/';
//var BOSH_SERVICE='http://172.16.2.140:7171/http-bind/';
var BOSH_SERVICE = 'http://172.16.2.140/http-bind/http-bind/';
//var BOSH_SERVICE='http://218.2.231.35:9999/http-bind/';
var connection = null;

function log(msg) 
{
    $('#log').append('<div></div>').append(document.createTextNode(msg));
}

function onConnect(status)
{

	console.log('Strophe.Status.CONNECTING: ' + Strophe.Status.CONNECTING);
	console.log('Strophe.Status.CONNFAIL: ' + Strophe.Status.CONNFAIL);
	console.log('Strophe.Status.DISCONNECTING: ' + Strophe.Status.DISCONNECTING);
	console.log('Strophe.Status.DISCONNECTED: ' + Strophe.Status.DISCONNECTED);
	console.log('Strophe.Status.CONNECTED: ' + Strophe.Status.CONNECTED);
	console.log('Strophe.Status.AUTHENTICATING: ' + Strophe.Status.AUTHENTICATING);
	console.log('Strophe.Status.AUTHFAIL: ' + Strophe.Status.AUTHFAIL);
	console.log('=============================');

	console.log(11211);
	console.log(connection);
	console.log(status);

    if (status == Strophe.Status.CONNECTING) {
		log('正在连接...');
        console.log('Strophe is connecting.');
    } else if (status == Strophe.Status.CONNFAIL) {
		log('Strophe failed to connect.');
		$('#connect').get(0).value = 'connect';
    } else if (status == Strophe.Status.DISCONNECTING) {
		log('Strophe is disconnecting.');
    } else if (status == Strophe.Status.DISCONNECTED) {
		log('Strophe is disconnected.');
		$('#connect').get(0).value = 'connect';
    } else if (status == Strophe.Status.CONNECTED) {
		log('连接成功！');
        console.log('Strophe is connected.');
//		log('ECHOBOT: Send a message to ' + connection.jid + ' to talk to me.');

		$.cookie('jid', connection.jid);
		$.cookie('sid', connection.sid);
		$.cookie('rid', connection.rid);
        
        // set jid to hidden field
        $('#fromjid').val(connection.jid);
        
        log(BOSH_SERVICE);
        
        // get friends
        var iq = $iq({type: 'get'}).c('query', {xmlns: 'jabber:iq:roster'});
        connection.sendIQ(iq, getFriends); // getFriends是回调函数
        
        connection.addHandler(onMessage, null, 'message', null, null,  null); 
        connection.addHandler(prececeOnOfLine, null, 'presence', null,  null,null); 
        connection.addHandler(handle_pong, null, 'iq', null,  'ping1'); 
        connection.send($pres().tree());
    	var handler = function(){
    		 var ping = $iq({to: 'jsvlepnode', type: "get", id: "ping1"}).c("ping", {xmlns: "urn:xmpp:ping"});
    		 connection.sendIQ(ping);
    		 log("send ping >>>");
        };
		var timerPing = setInterval( handler , 5000); //50秒发一次ping包 ct.sendpingtimer
    }
}
function handle_pong(){
	log("receve ping >>>");
	return true;
}
function prececeOnOfLine(pre){
	 log("cc"+Strophe.serialize(pre));
	return true;
}
function onMessage(msg) {
    var to = msg.getAttribute('to');
    var from = msg.getAttribute('from');
    var type = msg.getAttribute('type');
    var elems = msg.getElementsByTagName('body');

    if (type == "chat" && elems.length > 0) {
        var body = elems[0];
        
        log(new Date().toLocaleTimeString() + ' ' + from + ': ' + Strophe.getText(body));
        
//        var reply = $msg({to: from, from: to, type: 'chat'}).cnode(Strophe.copyElement(body));
//        connection.send(reply.tree());
//        log('ECHOBOT: I sent ' + from + ': ' + Strophe.getText(body));
    }

    // we must return true to keep the handler alive.  
    // returning false would remove it after it finishes.
    return true;
}

function getFriends(iq){	
    $(iq).find('item').each(function () {
        var jid = $(this).attr('jid');
        var name = $(this).attr('name') || jid;
        
        $('#friendlist').html('');
        $('#friendlist').append('<li><span>'+ jid +'</span> <a href="#'+ jid +'">talk</a></li>');
        console.log(jid + ' - ' + name);
    });
}

$(document).ready(function () {
    connection = new Strophe.Connection(BOSH_SERVICE);

    // Uncomment the following lines to spy on the wire traffic.
    //connection.rawInput = function (data) { log('RECV: ' + data); };
    //connection.rawOutput = function (data) { log('SEND: ' + data); };

    // Uncomment the following line to see all the debug output.
    //Strophe.log = function (level, msg) { log('LOG: ' + msg); };


    $('#connect').bind('click', function () {
        var button = $('#connect').get(0);
        if (button.value == 'connect') {
            button.value = 'disconnect';

            connection.connect($('#jid').get(0).value,
                       $('#pass').get(0).value,
                       onConnect);
        } else {
            button.value = 'connect';
            connection.disconnect();
        }
    });
    
    $('#send').bind('click', function () {
       
        
        var msg=$('#msg').val();
        toId = $('#tojid').val();
        fromId = $('#fromjid').val();
        
        console.log(msg);
        console.log(toId);
        
	    var reply = $msg({id:'afsds',to: toId, from: fromId , type: 'chat'}).cnode(Strophe.xmlElement('body', '' ,msg));
	    connection.send(reply.tree());
        log(new Date().toLocaleTimeString() + "  "+ fromId +":  "  + msg);
	    $('#msg').val('');
    });
    
    $('#friendlist li').bind('click', function () {
        var jid = $(this).find('span').text();
        $('#tojid').val(jid);
    });
});

